Ruby: self


Posted by Wendy on 2022-01-29

在Ruby的開發中,有時候會看到self這個字,那他究竟代表什麼,要怎麼使用呢?

什麼是self

self是一個Ruby的Keyword,簡單來說就是現在正在執行的物件(current object),而"current object"則取決於現在的"context",會有不同的結果,這樣講可能還有點模糊,不如直接來看看使用的情形。

In a method

在method中,self就是呼叫method的物件

class Animal
  def instance_self
    puts self
  end

  def self.class_self
    puts self
  end
end

aa = Animal.new
aa.instance_self
=> #<Animal:0x00007faba809a9d8>

Animal.class_self
=> Animal
  • 在instance method中,可以看到self會指向object本身
  • 在class method中,self則會指向class

In a class or module definition

這邊是指不在任何method中,self就是被定義好的class / module

class Animal
  puts "From class:"
  self
end

module Action
  puts "From module:"
  self
end

# result
From class:
=> Animal
From module:
=> Action

Default receives message

self 還有一個特性,當method沒有明確的receiver時,他就會是自動接收訊息

class Animal
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def upcase_name
    name.upcase
  end
end

dog = Animal.new('Lucky')
dog.upcase_name
=> "LUCKY"

這裡可以看到,在upcase_name中,並沒有指定是誰的name,但預設的receiver會是self,所以實際上應該是self.name.updcase,因為這是一個instance method,self是object本身,所以實際上當然就是回傳"LUCKY"囉!

看到這邊,應該對self有基本的概念了,下次看到它,就大概可以知道它代表什麼意思啦~


參考資料

ruby doc
Understanding self in Ruby


#ruby #self







Related Posts

Javascript replace space with regex

Javascript replace space with regex

解構賦值 destructuring assignment

解構賦值 destructuring assignment

Avoid blocking by navigation menu on mobile device

Avoid blocking by navigation menu on mobile device


Comments